package com.cy.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cy.bean.GameList;
import com.cy.service.AddGameService;
import com.cy.service.AddGameServiceImpl;

/**
 * Servlet implementation class AddGameServlet
 */
@WebServlet("/addgame")
public class AddGameServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置前端页面传递回来的字符编码
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");

		String action = request.getParameter("action");
		AddGameService addGameService = new AddGameServiceImpl();
		if (action == null) {
			// 跳转到添加页面
			request.setAttribute("mainRight", "/WEB-INF/jsp/addgame.jsp");
			request.getRequestDispatcher("/WEB-INF/jsp/main.jsp").forward(request, response);
		} else if (action != null && action.equals("add")) {
			String gamename = request.getParameter("gamename");
			String publisher = request.getParameter("publisher");
			String pubdate = request.getParameter("pubdate");
			String introduce = request.getParameter("introduce");
			String type = request.getParameter("type");
			boolean flag = addGameService.findGameByName(gamename);
			if (flag) {
				GameList game = new GameList(0, gamename, publisher, pubdate, introduce, type, 1);
				flag = addGameService.addGame(game);
				if (flag) {
					request.setAttribute("flag", 1);
				} else {
					request.setAttribute("flag", 2);
				}
			} else {
				request.setAttribute("flag", 3);
			}
			request.setAttribute("mainRight", "/WEB-INF/jsp/addgame.jsp");
			request.getRequestDispatcher("/WEB-INF/jsp/main.jsp").forward(request, response);
		}
	}

}
